package cn.fufeiii.bt.common.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 耗时过滤器
 *
 * @author FuFei
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(prefix = "logging.time-consuming", name = "enabled", havingValue = "true", matchIfMissing = true)
public class TimeConsumingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        long begin = System.nanoTime();
        log.info("开始请求接口:{}-{}", request.getMethod(), request.getServletPath());
        filterChain.doFilter(request, response);
        log.info("结束请求接口:{}-{} [{}ms]", request.getMethod(), request.getServletPath(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin));
    }

}
